package com.axis2.common.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


/**
 * @Description: ftp工具
 * @author xxliu
 * @create 2012-8-24 上午11:21:08
 */
public class FtpComponent {
	
	Logger log = LoggerFactory.getLogger(this.getClass());

    private FTPClient ftp;

    private final String FILE_FTP_PATH = "_file_ftp_path";
    /**
     * 建立连接
     * @param host 地址
     * @param port 端口号
     * @param username 用户名
     * @param password 密码
     * @return
     * @throws Exception
     */
    public FTPClient connect(String host,String port,String username,String password) throws Exception {
        if(ftp == null){
        	ftp = new FTPClient();
        }else if(ftp.isConnected()){
        	ftp.disconnect();
        }
            
        ftp.setControlEncoding("GBK");
        ftp.connect(host, Integer.parseInt(port));
        ftp.login(username,password);
        ftp.enterLocalPassiveMode();
        ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            ftp.disconnect();
            log.error("FTP连接失败。");
            throw new Exception("FTP连接失败。");
        }
        return ftp;
    }

    /**
     * 关闭连接
     * @throws Exception
     */
    public void disconnect() throws Exception {
        if(ftp != null && ftp.isConnected()){
            ftp.logout();
            ftp.disconnect();
        }
    }

    /**
     * @param dirPath 创建目录
     * @throws Exception
     */
    public void mkdir(String dirPath) throws IOException{
        String[] pathArr = dirPath.split("/");
        for(String path : pathArr){
            if(StringUtils.isNotBlank(path)){
                if(!ftp.changeWorkingDirectory(path)){
                    ftp.makeDirectory(path);
                    ftp.changeWorkingDirectory(path);
                }
            }
        }
    }

    /**
     * @param uploadPath 上传路径
     * @param file 上传的文件
     * @throws Exception
     */
    public void upload(File file,String uploadPath) throws Exception{
        FileInputStream input = new FileInputStream(file);
        try{
            if(!ftp.changeWorkingDirectory(uploadPath)){
                mkdir(uploadPath);
            }
            //[*1*] start
            if(ftp.storeFile(file.getName(), input)){
//            boolean flag = ftp.storeFile(new String(file.getName().getBytes("GBK"),"ISO-8859-1"), input);
//            if(flag) {
            	log.info("对账单文件" + file.getName() + "上传至" + uploadPath + "成功");
            }else{
            	log.info("对账单文件" + file.getName() + "上传至" + uploadPath + "失败");
            }
            //[*1*] end
        }catch(Exception e) {
            log.info("上传文件至FTP出错：", e);
            e.printStackTrace();
        }finally {
            try {
                if(input != null){
                    input.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    
    public void upFtp(String host,String port,String userName,String password,File file,String filePath) throws Exception{
    	this.connect(host, port, userName, password);
    	this.upload(file, filePath);
    	this.disconnect();
    }
}
